package com.easyoffer.interception;

import cn.dev33.satoken.stp.StpUtil;
import com.easyoffer.annotation.RoleCheck;
import com.easyoffer.constant.UserConstant;
import com.easyoffer.enums.UserRoleEnum;
import com.easyoffer.exception.BusinessException;
import com.easyoffer.model.vo.UserVO;
import com.easyoffer.common.ErrorCode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户权限校验
 */
@Component
@Aspect
public class AuthInterception {
    @Around("@annotation(roleCheck)")
    public Object authCheckInterception(ProceedingJoinPoint joinPoint, RoleCheck roleCheck) throws Throwable {
        //必须要的权限
        String mustRole = roleCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限情况下放行
        if ("".equals(mustRole) || mustRoleEnum == null)
            return joinPoint.proceed();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Object obj = StpUtil.getSession().get(UserConstant.USER_LOGIN_STATE);
        //需要权限但未登录拒绝
        if (obj == null)
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        UserVO userVO = (UserVO) obj;
        UserRoleEnum roleEnum = UserRoleEnum.getEnumByValue(userVO.getUserRole());
        //被封号直接拒绝
        if (UserRoleEnum.BAN.equals(roleEnum))
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        //需要管理员权限没有直接拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) )
            if (!UserRoleEnum.ADMIN.equals(roleEnum))
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        return joinPoint.proceed();
    }


}
